<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of c_apply_event_controller
 *
 * @author tonatos
 */
class c_apply_event_controller extends c_base_controller{

    public function index($params){
        global $modx, $mvc;

        if (!empty($_GET['send'])){
            return "<h3>Ваша заявка отправлена</h3>";
        }

	$is_full = (!empty($params[2])) ? true:false;

        $form = new c_form_controller();
        $form->add_varchar("fio","ФИО","",true);

	if ($is_full){
	    $form->add_varchar("vozrast","Возраст","",true);
	    $form->add_varchar("razrad","Разряд","",true);
	    $form->add_varchar("passport","Серия и номер паспорта","",true);
	    $form->add_varchar("passport_date","Когда и где выдан паспорт","",true);
	    $form->add_varchar("city","Город","",true);
	
	}


        $form->add_varchar("tel","Телефон","",true);
        $form->add_email("email","E-mail")->check_web_user(false);
        $form->add_text("message", "Комментарий");
        $form->submit_text="Отправить";

        $this->id_user = $modx->getLoginUserID();

        if (!$this->id_user){
            $form->add_checkbox("register", "Зарегистрировать меня на сайте","Зарегистрированные пользователи получают уведомления о новых мероприятиях ТРФА");
        }

        if ($form->data_submitted()){
            if ($form->is_validate()){
                $data = $form->get_data();

                $parent = $modx->db->get_record("site_content","id = ".$modx->documentObject['parent']);
                if (!$parent){
                    $parent = $modx->db->get_record("site_content","id = ".$modx->documentIdentifier);
                }

                //Отправляем письмо менеджеру
                $this->data = (object)$data;
                $this->subject = $parent->pagetitle;
                $this->subject_link = $modx->makeUrl($parent->id,'','','full');

                $body = $this->show( $is_full?"mail_full":"mail_short",true);

                $this->send_mail("tonatos@gmail.com", $this->subject,$body);
                $this->send_mail("teent@bk.ru", $this->subject,$body);

                //Сохраняем данные

                $model = new c_apply_event_model();
                $model->id_doc = $parent->id;
                $model->fio = $data['fio'];
                $model->email = $data['email'];
                $model->tel = $data['tel'];
                $model->comment = $data['message'];
		$model->data = array("vozrast"=>$data['vozrast'],"razrad"=>$data['razrad'],
			"passport"=>$data['passport'],"passport_date"=>$data['passport_date'],"city"=>$data['city']);

                $model->save();

                global $mvc;
                $mvc->full_clear_cache();
                
                //Блок регистрации
                if ($data['register']==1){

                    $find_user = new c_web_users_model();
                    
                    if ($find_user->find_by_email($data['email'])===true){

                        //Пользователь зарегестрирован отправляем уведомление
                        $find_user->load();
                        $this->find_user = $find_user;
                        $this->subscribe_link = $modx->config['site_url']."cabinet/subscribe.html";

                        $body = $this->show("mail_find_user",true);

                        $this->send_mail($find_user->email, "Напоминание учетных данных на сайте ТРФА",$body);

                        
                    }else{

                        $need_redirect = false;
                        
                        //проверяем хватает ли данных для регистрации
                        if (empty($data['email'])) {
                            $need_redirect = true;
                        }else{
                            //вырезаем логин из email
                            $username = $modx->db->escape(substr($data['email'],0,strpos($data['email'], "@")));
                            $data['username'] = $username;
                            //ищем по логину
                            if ($modx->db->get_record("web_users","lower(username)=lower('$username')")!==false){
                                $need_redirect = true;
                            }else{

                                //Всех данных хватает, регистрируем
                                $register = new c_register_controller();

                                $user_data = array();
                                $user_data['username']=$username;
                                $user_data['fullname'] = $data['fio'];
                                $user_data['email'] = $data['email'];

                                $register->call_protected("register_with_activate",$user_data);

                            }
                            
                        }

                        if ($need_redirect){

                            $this->data = $data;
                            $this->show("need_redirect");
                            return;
                        }

                    }
                }

                $this->redirect($modx->makeUrl($modx->documentIdentifier,'','send=1'));
            }
        }else{
            if ($this->id_user){
                $user = new c_web_users_model($this->id_user);
                $form->get_field('fio')->set_value($user->fullname);
                $form->get_field('email')->set_value($user->email);

            }else{
                $form->get_field('register')->set_value(1);
            }
        }

        echo $form->show_form();
        
    }

    public function show_counter($params){
        global $modx;

        if (!empty($params[2])){
            $id_doc = (int)$params[2];
        }

        if (empty($id_doc)) $id_doc = $modx->documentIdentifier;

        $rows = $modx->db->get_records("apply_event","id_doc=$id_doc");

        $count = count($rows);

        if (!empty($params[3])){
            return $count;
        }

	$txt = empty($_SESSION['mgrValidated']) ? "(заявок: <strong>$count</strong>)" : "(<a href='/assets/snippets/mvc/apply_event/show_list/$id_doc'>заявок: <strong>$count</strong></a>)" ;
	

        return ($count>0) ? $txt : "" ;
    }

    public function show_list($params){
	global $mvc, $modx;
	$id_doc = (int)$params[2];

	$this->event = $modx->db->get_record("site_content","id=$id_doc");
	
	if (empty($_SESSION['mgrValidated'])){
		$this->redirect($id_doc);
	}

	$events = $modx->db->get_records("apply_event","id_doc=$id_doc");

	$table = new c_table();
	$table->setHead(array("№","ФИО","E-mail","Телефон","Комментарий","Дополнительно","Управление"));

	$i=1;
	foreach($events as $row){


		$add = "";

		$row->data = unserialize($row->data);

		if (!empty($row->data)){

			foreach($row->data as $key=>$value){

				switch ($key){
					case "vozrast": $key="Возраст";break;
					case "razrad": $key="Разряд";break;
					case "passport": $key="Паспорт";break;
					case "passport_date": $key="Паспорт";break;
					case "city": $key="Город";break;
				}
				
				$add .= "$key: $value<br/>";
			}
		}


		$table->addRow(array($i++,$row->fio, !empty($row->email)? "<a href='mailto:$row->email'>$row->email</a>": "",$row->tel,$row->comment,$add,""));
	}

	$this->table = $table;

	$this->show("show_list");
	

	
    }
}
?>
